Lumen & Gesso / website · lumengesso.com / app / api / admin / orders / [id] / cancel / route.ts
| 1 | import { NextResponse, after, type NextRequest } from 'next/server'; |
| 2 | import { getCustomerUser } from '@/app/lib/lumen-auth'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { isAdmin } from '@/app/lib/admin'; |
| 5 | import { stripe } from '@/app/lib/stripe'; |
| 6 | import { sendEmail } from '@/app/lib/email'; |
| 7 | import { env } from '@/app/lib/env'; |
| 8 | import { displayOrderId } from '@/app/lib/orders'; |
| 9 | import { cancellationByStudioHtml, cancellationStudioInternalHtml } from '@/app/lib/order-emails'; |
| 10 | |
| 11 | export const runtime = 'nodejs'; |
| 12 | export const dynamic = 'force-dynamic'; |
| 13 | |
| 14 | // Admin-initiated cancel. Broader than the customer-side cancel |
| 15 | // (which only works at `pending_design`) — admin can cancel from |
| 16 | // any non-terminal status. Stripe refund auto-fires when there's a |
| 17 | // payment_intent on file. Prodigi orders are NOT auto-cancelled — |
| 18 | // if `prodigi_order_id` is set, admin must cancel via Prodigi |
| 19 | // dashboard / API separately (handled out of band for now). |
| 20 | // |
| 21 | // 'abandoned' is also terminal here — there's no charge to refund |
| 22 | // and nothing to cancel; just leave the row alone. |
| 23 | const TERMINAL_STATUSES = new Set(['cancelled', 'abandoned']); |
| 24 | |
| 25 | export async function POST( |
| 26 | req: NextRequest, |
| 27 | ctx: { params: Promise<{ id: string }> }, |
| 28 | ) { |
| 29 | const { id } = await ctx.params; |
| 30 | |
| 31 | const user = await getCustomerUser(); |
| 32 | if (!user || !isAdmin(user.email)) { |
| 33 | return NextResponse.json({ error: 'forbidden' }, { status: 403 }); |
| 34 | } |
| 35 | |
| 36 | let body: { reason?: string }; |
| 37 | try { |
| 38 | body = await req.json(); |
| 39 | } catch { |
| 40 | body = {}; |
| 41 | } |
| 42 | const reason = (body.reason ?? '').trim() || null; |
| 43 | |
| 44 | const admin = commerceDb(); |
| 45 | const { data: order, error: fetchErr } = await admin |
| 46 | .from('orders') |
| 47 | .select('id, user_email, status, price_cents, stripe_payment_intent_id, prodigi_order_id') |
| 48 | .eq('id', id) |
| 49 | .single(); |
| 50 | |
| 51 | if (fetchErr || !order) { |
| 52 | return NextResponse.json({ error: 'Order not found.' }, { status: 404 }); |
| 53 | } |
| 54 | if (TERMINAL_STATUSES.has(order.status)) { |
| 55 | return NextResponse.json({ |
| 56 | error: `Order is already in terminal state "${order.status}". Nothing to cancel.`, |
| 57 | }, { status: 409 }); |
| 58 | } |
| 59 | |
| 60 | // Issue Stripe refund if there's a payment intent. Skip if no |
| 61 | // charge exists yet (status: pending_payment). |
| 62 | let refundId: string | null = null; |
| 63 | let refundError: string | null = null; |
| 64 | if (order.stripe_payment_intent_id) { |
| 65 | try { |
| 66 | const refund = await stripe().refunds.create({ |
| 67 | payment_intent: order.stripe_payment_intent_id, |
| 68 | reason: 'requested_by_customer', |
| 69 | metadata: { orderId: order.id, source: 'admin-cancel', cancelReason: reason ?? '' }, |
| 70 | }); |
| 71 | refundId = refund.id; |
| 72 | } catch (e) { |
| 73 | console.error('[admin cancel] Stripe refund failed', e); |
| 74 | refundError = e instanceof Error ? e.message : 'refund failed'; |
| 75 | // Don't fail the whole cancel on a refund error — admin can |
| 76 | // refund manually from the Stripe dashboard. Surface in |
| 77 | // response so admin knows. |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // Warn if a Prodigi order exists — admin needs to cancel that |
| 82 | // separately via Prodigi's UI/API. We mark our order cancelled |
| 83 | // regardless so internal status reflects intent. |
| 84 | const prodigiWarning = order.prodigi_order_id |
| 85 | ? `This order already has a Prodigi reference (${order.prodigi_order_id}). Cancel the Prodigi order separately via dashboard/API — this endpoint does not auto-cancel print orders.` |
| 86 | : null; |
| 87 | |
| 88 | await admin.from('orders').update({ |
| 89 | status: 'cancelled', |
| 90 | }).eq('id', id); |
| 91 | |
| 92 | // Notify the customer (separate template from customer-initiated |
| 93 | // cancel — phrased as "we've cancelled" with an optional reason). |
| 94 | // Sent in after() so a slow/stalled email send can't hold the HTTP response |
| 95 | // open — the refund + status flip above are the parts the admin waits on; |
| 96 | // email delivery is a side effect that runs after we've responded. |
| 97 | after(async () => { |
| 98 | await Promise.allSettled([ |
| 99 | sendEmail({ |
| 100 | to: order.user_email, |
| 101 | subject: `Cancelled by Lumen & Gesso — ${displayOrderId(order.id)}`, |
| 102 | html: cancellationByStudioHtml(order.id, order.price_cents, reason), |
| 103 | text: `Your commission ${displayOrderId(order.id)} has been cancelled by our studio.${reason ? ` Reason: ${reason}.` : ''} A full refund of $${(order.price_cents / 100).toFixed(2)} has been issued${refundError ? ' (or will be — refund processing failed, the studio will follow up manually)' : ''} and typically lands within 5–10 business days.`, |
| 104 | }), |
| 105 | // Internal record so the studio inbox has a copy. |
| 106 | sendEmail({ |
| 107 | to: env.site.studioEmail(), |
| 108 | subject: `[ADMIN CANCEL] ${displayOrderId(order.id)} — ${order.user_email}`, |
| 109 | html: cancellationStudioInternalHtml(order.id, order.user_email, order.price_cents, { |
| 110 | reason, |
| 111 | refundId, |
| 112 | refundError, |
| 113 | prodigiOrderId: order.prodigi_order_id, |
| 114 | }), |
| 115 | text: `Admin cancelled order ${order.id} (${order.user_email}). Refund: ${refundId ?? (refundError ? 'FAILED — ' + refundError : 'no charge to refund')}. Prodigi: ${order.prodigi_order_id ?? 'none'}. Reason: ${reason ?? '(none)'}`, |
| 116 | }), |
| 117 | ]); |
| 118 | }); |
| 119 | |
| 120 | return NextResponse.json({ |
| 121 | ok: true, |
| 122 | refundId, |
| 123 | refundError, |
| 124 | prodigiWarning, |
| 125 | }); |
| 126 | } |